import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../utils/logger.dart';

class WebPage extends StatefulWidget {
  final Map<String, dynamic> arguments;

  const WebPage(this.arguments, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  late String url;
  late WebViewController controller;
  String title = '...';

  @override
  void initState() {
    super.initState();
    url = widget.arguments['url'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        actions: [
          IconButton(
              onPressed: () {
                launchUrl(Uri.parse(url));
              },
              icon: const Icon(Icons.input)),
        ],
      ),
      extendBodyBehindAppBar: true,
      backgroundColor: Colors.white,
      body: SafeArea(
        child: WebView(
          initialUrl: url,
          onWebViewCreated: (webController) {
            controller = webController;
          },
          onPageStarted: (value) {
            logger.info('page start: $value');
          },
          onPageFinished: (value) async {
            String? pageTitle = await controller.getTitle();
            logger.info('page finished: $value');
            if (pageTitle == null) {
              return;
            }
            logger.info('title: $pageTitle');
            setState(() {
              title = pageTitle;
            });
          },
          javascriptMode: JavascriptMode.unrestricted,
        ),
      ),
      bottomNavigationBar: null,
    );
  }
}
